"""
功能：演示NBIOT模组的TCP透传
公众号：玖零大壮
"""

import socketserver


# 按照16进制打印字符串
def print_hex(_bytes):
    _val = [hex(int(i)) for i in _bytes]
    print(' '.join(_val))


class MyThreadingTCPServer(socketserver.ThreadingTCPServer):
    """重写socketserver.ThreadingTCPServer"""
    # 服务停止后即刻释放端口，无需等待tcp连接断开
    allow_reuse_address = True


class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        try:
            while True:
                self.data = self.request.recv(1024)
                print("{} send:".format(self.client_address), self.data)
                if not self.data:
                    print("Connection Lost")
                    break
                # 将数据发回至客户端
                self.request.sendall(self.data)
                # 打印接收到的16进制数据
                print_hex(self.data)

        except Exception as e:
            print(self.client_address, "Connection Disconnected")
        finally:
            self.request.close()

    def setup(self):
        print("New Connection：", self.client_address)

    def finish(self):
        print("Finish")


if __name__ == '__main__':
    HOST, PORT = "0.0.0.0", 10001
    server = MyThreadingTCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

